<template>
  <block v-if="subject">
    <div class="card">
      <div class="little">{{ subject.typeName }}</div>
      <div class="title">
        <text v-if="subject.is_require" class="required">*</text>{{ subject.title }}
      </div>
      <div v-if="subject.SUBJECT_HINT" class="hint">{{ subject.SUBJECT_HINT }}</div>
      <div v-if="subject.unAnswer" class="un-answer">这道题未完整回答</div>

      <u-radio-group
        v-if="subject.type == 'u-radio'"
        v-model="subject.payload.value"
        :placement="placement"
        icon-placement="right"
        active-color="#78FFE6"
        active-label-color="#78FFE6"
        :img-class="placement == 'row'"
        @change="radioChange"
      >
        <block v-for="option in subject.options" :key="option.ID">
          <block v-if="!option.OPTION_PHOTO">
            <view v-show="option.citeShow && option.optionAssShow" style="margin-bottom: 32rpx;">
              <u-radio :label="option.OPTION_NAME" :name="option.ID" :line-height="1.5">
                <template #icon>
                  <div class="inner-circle" />
                </template>
              </u-radio>
              <u--input
                v-if="option.input"
                v-model="option.value"
                placeholder="请输入"
                border="bottom"
                clearable
                :adjust-position="false"
                @input="(val) => {
                  debounceRadioInputChange(option, val)
                }"
              />
              <div v-if="option.placeholder" class="placeholder">
                {{ option.placeholder }}
              </div>
            </view>
          </block>
          <block v-else>
            <view v-show="option.citeShow && option.optionAssShow" class="img-container">
              <view class="img-box">
                <img :src="option.OPTION_PHOTO" alt="" mode="widthFix" style="width: 288rpx;">
              </view>
              <view style="margin-top: 32rpx;">
                <u-radio :label="option.OPTION_NAME" :name="option.ID" :line-height="1.5">
                  <template #icon>
                    <div class="inner-circle" />
                  </template>
                </u-radio>
                <u--input
                  v-if="option.input"
                  v-model="option.value"
                  placeholder="请输入"
                  border="bottom"
                  clearable
                  :adjust-position="false"
                  @input="(val) => {
                    debounceRadioInputChange(option, val)
                  }"
                />
                <div v-if="option.placeholder" class="placeholder">
                  {{ option.placeholder }}
                </div>
              </view>
            </view>
          </block>
        </block>
      </u-radio-group>
      <u-checkbox-group
        v-if="subject.type == 'u-checkbox'"
        v-model="subject.payload.value"
        :placement="placement"
        :img-class="placement == 'row'"
        icon-placement="right"
        active-color="#78FFE6"
        active-label-color="#78FFE6"
        @change="checkboxChange"
      >
        <block v-for="option in subject.options" :key="option.ID">
          <block v-if="!option.OPTION_PHOTO">
            <view v-show="option.citeShow && option.optionAssShow" style="margin-bottom: 32rpx;">
              <u-checkbox
                :label="option.OPTION_NAME"
                :name="option.ID"
                :line-height="1.5"
                :disabled="option.disabled"
                @change="(bool) => singleCheckboxChange(option, bool)"
              />
              <u--input
                v-if="option.input"
                v-model="option.value"
                placeholder="请输入"
                border="bottom"
                clearable
                :adjust-position="false"
                @input="(val) => {
                  debounceCheckboxInputChange(option, val)
                }"
              />
              <div v-if="option.placeholder" class="placeholder">
                {{ option.placeholder }}
              </div>
            </view>
          </block>
          <block v-else>
            <view v-show="option.citeShow && option.optionAssShow" class="img-container">
              <view class="img-box">
                <img :src="option.OPTION_PHOTO" alt="" mode="widthFix" style="width: 288rpx;">
              </view>
              <view style="margin-top: 32rpx;">
                <u-checkbox
                  :label="option.OPTION_NAME"
                  :name="option.ID"
                  :line-height="1.5"
                  :disabled="option.disabled"
                  @change="(bool) => singleCheckboxChange(option, bool)"
                />
                <u--input
                  v-if="option.input"
                  v-model="option.value"
                  placeholder="请输入"
                  border="bottom"
                  clearable
                  :adjust-position="false"
                  @input="(val) => {
                    debounceCheckboxInputChange(option, val)
                  }"
                />
                <div v-if="option.placeholder" class="placeholder">
                  {{ option.placeholder }}
                </div>
              </view>
            </view>
          </block>
        </block>
      </u-checkbox-group>

      <div
        v-if="subject.type == 'u-picker' && subject.options.filter(o => o.citeShow).length"
        @click="showPicker = true"
      >
        <u--input
          v-model="subject.payload.text"
          placeholder="请下拉选择你最想要的选项"
          border="surround"
          suffix-icon="arrow-down"
          suffix-icon-style="color: #D6D9DB"
          disabled-color="#fff"
          disabled
        />
      </div>

      <block v-if="subject.type == 'u-input'">
        <u--textarea
          v-if="!subject.STYLE"
          v-model="subject.payload.value"
          placeholder="请输入"
          border="surround"
          height="24"
        />
        <u--textarea v-else v-model="subject.payload.value" placeholder="请输入" :adjust-position="false" />
        <div v-if="subject.OPTION_MIN" class="imgTips">最少输入{{ subject.OPTION_MIN }}个字符</div>
      </block>
      <block v-if="subject.type == 'u-slider'">
        <div class="slider">
          <div class="input">
            <u--input
              v-model="subject.payload.value"
              placeholder="请输入"
              border="surround"
              type="number"
              :font-size="subject.payload.value ? 12 : 10"
              @change="slideInputChange"
            />
          </div>
          <div class="slider-right">
            <div class="slider-text">
              <text>{{ subject.OPTION_MIN_TEXT }}({{ subject.OPTION_MIN }})</text>
              <text>{{ subject.OPTION_MAX_TEXT }}({{ subject.OPTION_MAX }})</text>
            </div>

            <u-slider
              v-model="subject.payload.value"
              block-color="#E3CFA5"
              inactive-color="#D6D9DB"
              active-color="#E3CFA5"
              block-size="12"
              @change="sliderChange"
            >
              <div class="slider-ticks">
                <div
                  v-for="(tick, index) in subject.ticks"
                  :key="index"
                  class="slider-tick"
                  :style="{ left: `${tick.left}%` }"
                  :class="{ 'slider-tick__active': tick.active }"
                />
              </div>
              <div class="slider-nums">
                <div
                  v-for="(tick, index) in subject.ticks"
                  :key="index"
                  class="slider-num"
                  :style="{ left: `${tick.left}%` }"
                >
                  <text v-if="tick.showNum">{{ tick.step }}</text>
                </div>
              </div>
            </u-slider>
          </div>
        </div>
      </block>

      <div v-if="subject.type == 'nfs'" class="nfs">
        <div class="nfs-text">
          <text>{{ subject.OPTION_MIN_TEXT }}({{ subject.OPTION_MIN }})</text>
          <text>{{ subject.OPTION_MAX_TEXT }}({{ subject.OPTION_MAX }})</text>
        </div>
        <div class="nfs-content">
          <div v-for="(item, index) in subject.nfs" :key="index" class="nfs-item">
            <div class="nfs-item__inner" :class="{ 'no-border_right': index == subject.nfs.length - 1 }">
              {{ item.i }}
            </div>
          </div>
          <div class="nfs-position">
            <div
              v-for="(item, index) in subject.nfs"
              :key="index"
              class="nfs-item nfs-white"
              :class="{ 'nfs-transparent': item.active }"
              @click="nfsClick(index)"
            >
              <div class="nfs-item__inner nfs-gray" :class="{ 'no-border_right': index == subject.nfs.length - 1 }">
                {{ item.i }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="subject.type == 'location'" style="text-align: center;" class="location">
        <div @click="getLocation">
          <u--input
            v-model="subject.payload.address"
            placeholder="点击获取当前位置"
            suffix-icon="map"
            font-size="12"
            disabled
            disabled-color="#fff"
          />
        </div>
        <div v-if="subject.payload.address" class="location-retry" @click="getLocation">重新获取定位</div>
      </div>
      <div v-if="subject.type == 'star'" class="star">
        <l-star-rate v-model="subject.payload.value" un-active-color="#EBEDF0" active-color="#78FFE6">
          <div class="star-word">
            <text>非常不满意</text>
            <text style="margin-left: auto;">非常满意</text>
          </div>
        </l-star-rate>
      </div>
      <div v-if="subject.type == 'u-datetime'">
        <div @click="datetimeShow = true">
          <u--input
            v-model="subject.payload.value"
            placeholder="请选择日期/时间"
            suffix-icon="calendar"
            font-size="12"
            disabled
            disabled-color="#fff"
          />
        </div>
      </div>
      <div v-if="subject.type == 'matrix-radio'">
        <block v-for="option in subject.options" :key="option.ID">
          <block v-if="option.citeShow">
            <div class="matrix-title">
              {{ option.OPTION_NAME }}
            </div>
            <u-radio-group
              v-model="subject.payload[option.ID].value"
              placement="column"
              icon-placement="right"
              active-color="#78FFE6"
              active-label-color="#78FFE6"
            >
              <u-radio
                v-for="option2 in subject.options2"
                :key="option2.ID"
                :custom-style="{ marginBottom: '16px' }"
                :label="option2.OPTION_NAME"
                :name="option2.ID"
              >
                <template #icon>
                  <div class="inner-circle" />
                </template>
              </u-radio>
            </u-radio-group>
          </block>
        </block>
      </div>

      <div v-if="subject.type == 'matrix-nfs'" class="nfs">
        <div v-if="subject.options.filter(o => o.citeShow).length" class="nfs-text">
          <text>{{ subject.OPTION_MIN_TEXT }}({{ subject.OPTION_MIN }})</text>
          <text>{{ subject.OPTION_MAX_TEXT }}({{ subject.OPTION_MAX }})</text>
        </div>
        <block v-for="option in subject.options" :key="option.ID">
          <block v-if="option.citeShow">
            <div class="matrix-title">
              {{ option.OPTION_NAME }}
            </div>
            <div class="nfs-content">
              <div v-for="(n, index) in option.nfs" :key="index" class="nfs-item">
                <div class="nfs-item__inner" :class="{ 'no-border_right': index == option.nfs.length - 1 }">
                  {{ n.i }}
                </div>
              </div>
              <div class="nfs-position">
                <div
                  v-for="(n, index) in option.nfs"
                  :key="index"
                  class="nfs-item nfs-white"
                  :class="{ 'nfs-transparent': n.active }"
                  @click="matrixNfsClick(option.ID, index)"
                >
                  <div class="nfs-item__inner nfs-gray" :class="{ 'no-border_right': index == option.nfs.length - 1 }">
                    {{ n.i }}
                  </div>
                </div>
              </div>
            </div>
            <div v-if="optionIndex < subject.options.length - 1" style="margin: 16px auto;">
              <u-line />
            </div>
          </block>
        </block>
      </div>

      <div v-if="subject.type == 'matrix-checkbox'">
        <block v-for="option in subject.options" :key="option.ID">
          <block v-if="option.citeShow">
            <div class="matrix-title">
              {{ option.OPTION_NAME }}
            </div>
            <u-checkbox-group
              v-model="subject.payload[option.ID].value"
              placement="column"
              icon-placement="right"
              active-color="#78FFE6"
              active-label-color="#78FFE6"
            >
              <u-checkbox
                v-for="option2 in subject.options2"
                :key="option2.ID"
                :custom-style="{ marginBottom: '16px' }"
                :label="option2.OPTION_NAME"
                :name="option2.ID"
              />
            </u-checkbox-group>
          </block>
        </block>
      </div>

      <div v-if="subject.type == 'matrix-star'" class="star">
        <block v-for="(option, index) in subject.options" :key="option.ID">
          <block v-if="option.citeShow">
            <div class="matrix-title">
              {{ option.OPTION_NAME }}
            </div>
            <l-star-rate v-model="subject.payload[option.ID].value" un-active-color="#EBEDF0" active-color="#78FFE6">
              <div class="star-word">
                <text>非常不满意</text>
                <text style="margin-left: auto;">非常满意</text>
              </div>
            </l-star-rate>
            <div v-if="index < subject.options.length - 1" style="margin: 16px auto;">
              <u-line />
            </div>
          </block>
        </block>
      </div>

      <block v-if="subject.type == 'multple-score'">
        <div>
          <div v-for="o in subject.options" :key="o.ID">
            <div class="title" style="margin-top: 32rpx;">{{ o.OPTION_NAME }}</div>
            <block v-if="o.SHOW_TYPE == 10">
              <u-radio-group
                v-model="o.value"
                placement="column"
                icon-placement="right"
                active-color="#78FFE6"
                active-label-color="#78FFE6"
                @change="(v) => multRadioChange(o, v)"
              >
                <block v-for="option in o.options" :key="option.ID">
                  <view style="margin-bottom: 32rpx;">
                    <u-radio :label="option.OPTION_NAME" :name="option.ID" :line-height="1.5">
                      <template #icon>
                        <div class="inner-circle" />
                      </template>
                    </u-radio>
                  </view>
                </block>
              </u-radio-group>
            </block>
            <block v-else>
              <l-star-rate
                v-model="o.value"
                un-active-color="#EBEDF0"
                active-color="#78FFE6"
                @change="(v) => multStarChange(o, v)"
              >
                <div class="star-word">
                  <text>非常不满意</text>
                  <text style="margin-left: auto;">非常满意</text>
                </div>
              </l-star-rate>
            </block>
            <block v-if="o.ADD_REASON_SCORE && o.showReasonValue">
              <div class="reason">
                为了更好的改进产品给您更好的体验，请描述原因
              </div>
              <div style="margin-top: 18rpx;">
                <u--textarea v-model="o.reasonValue" placeholder="请输入" :adjust-position="false" />
              </div>
            </block>
            <div style="margin-top: 56rpx;">
              <u-line />
            </div>
          </div>
        </div>
      </block>
      <block v-if="subject.type == 'u-image'">
        <!-- 容器 -->
        <view class="ui_uploader_cell">
          <!-- 根据已选择的图片临时路径数组展示图片-->
          <view
            style="display: flex;
                        align-items: center;
                        flex-wrap: wrap;
                        background: #fff;
                      "
          >
            <view v-for="(item, index) in subject.payload.value" :key="index" class="ui_uploader_item">
              <!-- 删除-->
              <div
                style="position: absolute; right: 24rpx;top:12rpx;width: 40rpx;
                          height: 40rpx;
                          background: #fff;
                          border-radius: 20rpx;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          opacity: 0.6;"
                @click="clearImg(index)"
              >
                <view
                  class="iconfont icon-close-circle-filled close-circle-filled"
                  style="font-size:40rpx;color: #000;"
                />
              </div>
              <!-- 图片-->
              <image
                :data-index="index"
                :src="item"
                mode="aspectFill"
                style="width: 192rpx; height: 192rpx; margin-right: 8px;border-radius: 8rpx;"
                @click="showImg"
              />
            </view>
            <!-- 上传按钮+框 -->
            <view v-if="showUpload" class="ui_uploader" @click="upload">
              <view style="font-size: 50rpx;color: #434343;" class="iconfont icon-icon-camera" />
            </view>
          </view>
        </view>
        <div v-if="subject.PIC_TYPE" class="imgTips">
          最多可上传{{ subject.OPTION_MAX }}张，最少上传{{ subject.OPTION_MIN }}张，支持{{ subject.PIC_TYPE }}格式
        </div>
        <div v-else class="imgTips">最多可上传{{ subject.OPTION_MAX }}张，最少上传{{ subject.OPTION_MIN }}张，不限格式</div>
      </block>
      <div v-if="subject.CITATION_SNO && !subject.options.filter(o => o.citeShow).length" class="no-options">
        此题选项来源于前面题目的选中项,请按顺序作答
      </div>
    </div>
    <u-picker
      v-if="subject.type == 'u-picker'"
      :show="showPicker"
      :columns="[subject.options.filter(o => o.citeShow)]"
      key-name="OPTION_NAME"
      confirm-color="#78FFE6"
      immediate-change
      @cancel="showPicker = false"
      @confirm="pickerConfirm"
    />
    <u-datetime-picker
      ref="datetimePicker"
      v-model="subject.payload.datetime"
      :show="datetimeShow"
      mode="datetime"
      :formatter="formatter"
      confirm-color="#78FFE6"
      min-date="852048000"
      @cancel="datetimeShow = false"
      @confirm="datetimeConfirm"
    />
    <canvas
      :id="'qrCanvas' + subject.SUBJECT_ID"
      class="qr-canvas"
      :canvas-id="'qrCanvas' + subject.SUBJECT_ID"
      type="2d"
      :style="'width:' +
        canvasContent.width +
        'px;height:' +
        canvasContent.height +
        'px'
      "
    />
  </block>
</template>

<script>
import {
  mapActions
} from 'vuex'
import lStarRate from '../components/l-starRate/l-starRate'
import dayjs from 'dayjs'
import {
  subjectMap
} from './subjectFn'
import {
  uploadImg
} from '@/api'
import config from '@/config'
import {
  getImg,
  debounce
} from '@/utils'
export default {
  components: {
    lStarRate
  },
  props: ['realSubject'],
  data() {
    return {
      showPicker: false,
      datetimeShow: false,
      subject: null,
      uploaderNum: 0,
      showUpload: true,
      canvasContent: {
        width: 0,
        height: 0,
        scale: 0
      }
    }
  },
  computed: {
    placement() {
      if (this.subject && (this.subject.SUBJECT_TYPE == 10 || this.subject.SUBJECT_TYPE == 11)) {
        const option = this.subject.options.find(o => o.OPTION_PHOTO)
        return option ? 'row' : 'column'
      }
      return 'column'
    }
  },
  watch: {
    subject: {
      handler() {
        this.updateSubject(this.subject)
        if (this.subject.isSonRelation) {
          setTimeout(() => {
            this.$emit('subjectRealtionChange', {
              sonList: this.subject.sonRelationSubjectIdList,
              subject: this.subject
            })
          })
        }
        if ([10, 11, 27, 29].includes(Number(this.subject.SUBJECT_TYPE)) && this.subject.isSonOptionRelation) {
          setTimeout(() => {
            this.$emit('subjectOptionRealtionChange', {
              sonList: this.subject.sonOptionRelationSubjectIdList,
              subject: this.subject
            })
          })
        }
        if (this.subject.unAnswer) {
          const {
            value
          } = subjectMap[this.subject.SUBJECT_TYPE].getSubjectValue(this.subject)
          if (value) this.subject.unAnswer = false
        }
      },
      deep: true
    },
    realSubject: {
      handler() {
        this.subject = this.realSubject
      },
      deep: true
    }
  },
  methods: {
    ...mapActions('subject', ['updateSubject']),
    skipLogic(id) {
      const option = this.subject.options.find(o => o.ID == id)
      if (option.SKIP) {
        // skip -1直接跳转下一题 其他为题号
        this.$emit('radioChange', {
          subject: this.subject,
          option,
          skip: Number(option.SKIP)
        })
      }
    },
    checkSkip(id) {
      if (this.subject.SKIP_SUBJECT_ID == -1) {
        // 下一题
        this.$emit('radioChange', {
          subject: this.subject,
          skip: -1
        })
      } else if (this.subject.SKIP_SUBJECT_ID == -2) {
        // 直接结束
        this.$emit('radioChange', {
          subject: this.subject,
          skip: -2
        })
      } else if (this.subject.SKIP_SUBJECT_ID == -3) {
        // 选项跳题
        this.skipLogic(id)
      } else {
        // 直接跳转题号
        this.$emit('radioChange', {
          subject: this.subject,
          skip: Number(this.subject.SKIP_SUBJECT_ID)
        })
      }
    },
    radioChange(value) {
      this.checkSkip(value)
    },
    radioInputChange(option, val) {
      if (val && this.subject.payload.value != option.ID) {
        this.subject.payload.value = option.ID
        this.checkSkip(option.ID)
      }
    },
    multStarChange(o, v) {
      if (o.ADD_REASON_SCORE) {
        const sno = o.options.find(option => option.ID == v).OPTION2_SNO
        if (o.ADD_REASON_SCORE >= sno) {
          o.showReasonValue = true
        } else {
          o.showReasonValue = false
        }
        const index = this.subject.options.findIndex(option => option.ID == o.ID)
        this.$set(this.subject.options[index], 'showReasonValue', o.showReasonValue)
      }
    },
    multRadioChange(o, v) {
      // 存在分数追问原因
      if (o.ADD_REASON_SCORE) {
        const sno = o.options.find(option => option.ID == v).OPTION2_SNO
        if (o.ADD_REASON_SCORE >= sno) {
          o.showReasonValue = true
        } else {
          o.showReasonValue = false
        }
        const index = this.subject.options.findIndex(option => option.ID == o.ID)
        this.$set(this.subject.options[index], 'showReasonValue', o.showReasonValue)
      }
    },
    // 是否存在互斥
    isHaveExclusion() {
      return this.subject.options.some(o => o.IS_EXCLUSION == 1)
    },
    checkboxChange(value, name) {
      if (this.subject.OPTION_MAX) {
        if (value.length >= this.subject.OPTION_MAX) {
          this.subject.options.forEach(o => {
            if (!value.includes(o.ID)) {
              o.disabled = true
            }
          })
        } else {
          this.subject.options.forEach(o => o.disabled = false)
        }
      }
    },
    singleCheckboxChange(option, bool) {
      // 自定义的函数,执行时机有问题,所以需要加上延迟
      setTimeout(() => {
        this.$emit('checkboxCiteFn', {
          subject: this.subject
        })
      }, 0)
      if (!bool) return
      setTimeout(() => {
        if (this.isHaveExclusion()) {
          if (option.IS_EXCLUSION == 1) {
            this.subject.payload.value = [option.ID]
          } else {
            const exclusion = this.subject.options.some(o => (this.subject.payload.value.includes(o
              .ID) && o.IS_EXCLUSION == 1))

            if (exclusion) {
              this.subject.payload.value = [option.ID]
            }
          }
        }
      }, 0)
    },
    checkboxInputChange(option, val) {
      if (option.disabled) return
      option.value = val
      if (val && !this.subject.payload.value.includes(option.ID)) {
        this.subject.payload.value.push(option.ID)
        this.singleCheckboxChange(option, true)
      }
    },
    pickerConfirm({
      value
    }) {
      this.$set(this.subject.payload, 'value', value[0].ID)
      this.$set(this.subject.payload, 'text', value[0].OPTION_NAME)
      this.showPicker = false
    },
    sliderChange(value) {
      this.subject.ticks.forEach(tick => {
        value >= tick.step ? tick.active = true : tick.active = false
      })
    },
    slideInputChange(value) {
      this.sliderChange(value)
    },
    nfsClick(index) {
      this.subject.nfs.forEach((item, itemIndex) => {
        if (index >= itemIndex) {
          item.active = true
        } else {
          item.active = false
        }
      })
      this.subject.payload.value = index
    },
    getSetting() {
      return new Promise((resolve) => {
        wx.getSetting({
          success(res) {
            resolve(res)
          }
        })
      })
    },
    getLocation() {
      wx.getLocation({
        type: 'gcj02',
        success: async(data) => {
          const {
            latitude,
            longitude,
            key
          } = data
          wx.chooseLocation({
            latitude,
            longitude,
            success: (res) => {
              const {
                address,
                name
              } = res
              this.$set(this.subject.payload, 'address', name)
              this.$set(this.subject.payload, 'address_detail', address)
              this.$set(this.subject.payload, 'value', JSON.stringify({
                address: name,
                address_detail: address
              }))
            },
            fail: (res) => {
              console.log('报错', res)
            }
          })
        },
        fail: async() => {
          const res = await this.getSetting()
          if (!res.authSetting['scope.userLocation']) {
            wx.showModal({
              title: '您未开启地理位置授权',
              content: '开启定位获得更好的服务',
              success: (res) => {
                if (res.confirm) wx.openSetting()
              }
            })
            return
          }
        }
      })
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },
    datetimeConfirm({
      value
    }) {
      this.subject.payload.value = dayjs(value).format('YYYY-MM-DD HH:mm')
      this.datetimeShow = false
    },
    matrixNfsClick(id, index) {
      this.subject.options.find(option => option.ID == id).nfs.forEach((item, itemIndex) => {
        if (index >= itemIndex) {
          item.active = true
        } else {
          item.active = false
        }
      })
      this.subject.payload[id].value = index
    },
    // 删除图片
    clearImg: function(index2) {
      var nowList = [] // 新数据
      var uploaderList = this.subject.payload.value // 原数据

      for (let i = 0; i < uploaderList.length; i++) {
        if (i == index2) {
          continue
        } else {
          nowList.push(uploaderList[i])
        }
      }
      this.uploaderNum = this.uploaderNum - 1
      this.subject.payload.value = nowList
      this.showUpload = true
      let arr = []
      this.subject.payload.examPic.forEach((item, index) => {
        if (index2 !== index) {
          arr.push(item)
        }
      })
      this.subject.payload.examPic = arr
    },
    // 展示图片
    showImg: function(e) {
      var that = this
      wx.previewImage({
        urls: that.subject.payload.value,
        current: that.subject.payload.value[e.currentTarget.dataset.index]
      })
    },
    getImageInfos(tempFilePaths) {
      return new Promise((resolve) => {
        wx.getImageInfo({
          src: tempFilePaths,
          success(res) {
            resolve(res)
          },
          fail(res) {
            console.log('fail', res)
          }
        })
      })
    },
    getFileInfos(value) {
      return new Promise((resolve) => {
        wx.getFileInfo({
          filePath: value.path,
          success(res) {
            Object.assign(res, value)
            resolve(res)
          },
          fail(res) {
            console.log('失败文件信息:', res)
          }
        })
      })
    },
    imageOnload(image) {
      return new Promise((resolve) => {
        image.onload = () => {
          resolve()
        }
      })
    },
    uploadImgs(tempFilePaths, filetype, length, width, height, name) {
      console.log(tempFilePaths, 'tempFilePaths')
      const that = this
      let uploaderList = this.subject.payload.value.concat(tempFilePaths)
      if (uploaderList.length == this.subject.OPTION_MAX) {
        that.showUpload = false
      }
      this.subject.payload.value = uploaderList
      this.uploaderNum = uploaderList.length
      return new Promise((resolve) => {
        uploadImg(tempFilePaths, {
          filetype,
          length,
          width,
          height,
          name,
          is_origin: 1
        }).then((res) => {
          Object.assign(res, {
            filetype: filetype
          })
          resolve(res)
        })
      })
    },
    getSelectQurey2(queryStr) {
      return new Promise((resolve) => {
        const query = this.createSelectorQuery()
        console.log(queryStr, query, 'queryStr')
        query
          .select(queryStr)
          .fields({
            id: true,
            node: true,
            size: true
          })
          .exec((res) => {
            console.log(res, 'res')
            resolve(res)
          })
      })
    },
    // 水印
    async watermark(file) {
      const {
        pixelRatio
      } = wx.getSystemInfoSync()
      let maxW = 1024
      let maxH = 1024
      let ratio // 图片压缩比
      let needCompress = false // 是否需要压缩
      function compressCall() {
        if (maxW < file.width) {
          ratio = file.width / maxW
          maxH = file.height / ratio
          needCompress = true
        }
        if (maxH < file.height) {
          needCompress = true
          ratio = file.height / maxH
          maxW = file.width / ratio
        }
        if (!needCompress) {
          maxW = file.width
          maxH = file.height
        }

        if (maxW * pixelRatio >= 1024 || maxH * pixelRatio >= 1024) {
          maxW = maxW * 0.9
          maxH = maxH * 0.9
          compressCall()
        }
      }
      compressCall()
      this.canvasContent.width = maxW
      this.canvasContent.height = maxH
      const query = await this.getSelectQurey2('#qrCanvas' + this.subject.SUBJECT_ID)
      const qrCanvas = query[0].node
      qrCanvas.width = maxW * pixelRatio
      qrCanvas.height = maxH * pixelRatio
      const ctx = qrCanvas.getContext('2d')
      ctx.clearRect(0, 0, maxW, maxH)
      let image = qrCanvas.createImage()
      image.src = file.path
      await this.imageOnload(image)
      ctx.drawImage(image, 0, 0, qrCanvas.width, qrCanvas.height)

      const fontSize = maxW * 0.07
      ctx.font = fontSize + 'px PingFangSC-Semibold, PingFang SC'
      ctx.fillStyle = 'rgba(255,255,255,0.7)'
      const text = ctx.measureText(this.subject.WATERMARK_TEXT)
      ctx.fillText(
        this.subject.WATERMARK_TEXT,
        qrCanvas.width * 0.9 - text.width,
        qrCanvas.height * 0.8
      )

      // 460*88
      // let hfsImage = qrCanvas.createImage();
      // hfsImage.src = `${config.IMG_URL}/hfs.png`;
      // await this.imageOnload(hfsImage);
      // const b = (this.canvasContent.width * 0.5 * (2 / 3)) / hfsImage.width;
      // const hfsImageCanvasHeight = b * hfsImage.height;
      // ctx.drawImage(
      // 	hfsImage,
      // 	qrCanvas.width * 0.9 -
      // 	this.canvasContent.width * 0.5 * (2 / 3) * pixelRatio,
      // 	qrCanvas.height * 0.8 -
      // 	hfsImageCanvasHeight * pixelRatio -
      // 	fontSize -
      // 	16 * pixelRatio,
      // 	this.canvasContent.width * pixelRatio * 0.5 * (2 / 3),
      // 	hfsImageCanvasHeight * pixelRatio
      // );

      const tempFilePath = await this.canvasToTempFilePath(
        0,
        0,
        maxW,
        maxH,
        maxW * pixelRatio,
        maxH * pixelRatio,
        'qrCanvas',
        qrCanvas
      )
      const res = await this.getImageInfos(tempFilePath)
      const watermarkImage = await this.getFileInfos(res)
      console.log('最终压缩:', watermarkImage)
      ctx.clearRect(0, 0, maxW, maxH)
      qrCanvas.width = 0
      qrCanvas.height = 0
      this.canvasContent.width = 0
      this.canvasContent.height = 0
      console.log('运行了')
      return watermarkImage
    },
    canvasToTempFilePath(
      x,
      y,
      width,
      height,
      destWidth,
      destHeight,
      canvasId,
      canvas
    ) {
      return new Promise((resolve, reject) => {
        wx.canvasToTempFilePath({
          x,
          y,
          width,
          height,
          destWidth,
          destHeight,
          canvasId,
          canvas,
          quality: 0.5,
          success(res) {
            resolve(res.tempFilePath)
          },
          fail(res) {
            console.log('报错', res)
            reject(res)
          }
        })
      })
    },
    checkImageFormat(file) {
      const allowedTypes = this.subject.PIC_TYPE.split(',')
      console.log(allowedTypes, file, 'filefilefilefile')
      const fileType = file

      if (allowedTypes.includes(fileType)) {
        // 文件类型合法
        console.log('文件格式符合要求。')
        return true
      } else {
        // 文件类型不合法
        console.log('不支持的文件格式。')
        return false
      }
    },
    // 上传图片
    upload: function(e) {
      var that = this
      let filetype
      let length
      let width
      let height
      wx.chooseMedia({
        mediaType: ['image'],
        count: this.subject.OPTION_MAX - that.uploaderNum, // 默认6
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          const tempFilePaths = res.tempFiles
          Promise.all(
            tempFilePaths.map((item) => {
              return that.getImageInfos(item.tempFilePath)
            })
          ).then((arr) => {
            Promise.all(arr.map((item) => that.getFileInfos(item))).then(
              async(files) => {
                for (let index = 0; index < files.length; index++) {
                  wx.showLoading({
                    title: '上传中',
                    mask: true
                  })
                  let file = files[index]
                  let fileName = file.path
                  let lastDotIndex = fileName.lastIndexOf('.')
                  let fileExtension = fileName.slice(lastDotIndex + 1).toLowerCase()
                  console.log('压缩前', fileExtension, file)
                  if (that.subject.PIC_TYPE && !that.checkImageFormat(fileExtension)) {
                    wx.hideLoading()
                    wx.showToast({
                      title: '不支持的文件格式。',
                      icon: 'none',
                      duration: 2000
                    })
                    return
                  }

                  let name = 'file'
                  const watermarkImage = await that.watermark(file)
                  try {
                    let upload = await that.uploadImgs(
                      watermarkImage.path,
                      watermarkImage.type,
                      watermarkImage.size,
                      watermarkImage.width,
                      watermarkImage.height,
                      name
                    )
                    console.log(upload, 'uploadupload')
                    let fileid = upload.fileid
                    that.fileid = fileid
                    if (!upload.fileid) {
                      wx.hideLoading()
                      wx.showToast({
                        title: '上传失败',
                        icon: 'none',
                        duration: 2000
                      })
                      uploaderList.splice(index, 1)
                      that.subject.payload.value.splice(index, 1)
                    } else {
                      that.subject.payload.examPic.push(getImg({
                        i: upload.fileid,
                        n: `a.${upload.filetype}`
                      }))
                    }
                    wx.hideLoading()
                  } catch (error) {
                    console.log(error)
                    wx.hideLoading()
                    wx.showToast({
                      title: '上传失败，请重新上传',
                      icon: 'none',
                      duration: 2000
                    })
                    that.subject.payload.value = []
                    return
                  }
                }
              }
            )
          })
        },
        fail: function(res) {
          console.log('fail', res)
          that.failUpload = true
        }
      })
    }
  },
  mounted() {
    this.subject = this.realSubject
    this.debounceRadioInputChange = debounce(this.radioInputChange)
    this.debounceCheckboxInputChange = debounce(this.checkboxInputChange)
  }
}
</script>

<style lang="scss" scoped>
	.hint {
		font-size: 28rpx;
		font-weight: 400;
		color: #969799;
		margin-bottom: 24rpx;
	}

	.reason {
		font-weight: 400;
		font-size: 28rpx;
		color: #8C8C8C;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
		margin-top: 32rpx;
	}

	.img-container {
		width: 320rpx;
		border-radius: 8rpx;
		outline: 2rpx solid #E7E7E7;
		box-sizing: border-box;
		flex-shrink: 0;
		margin-bottom: 16rpx;
		padding: 16rpx;
		overflow: hidden;

		.img-box {
			width: 288rpx;
			height: 288rpx;
			overflow: hidden;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.img-container:nth-of-type(odd) {
		margin-right: 14rpx;
	}

	.placeholder {
		font-weight: 400;
		font-size: 24rpx;
		color: #8C8C8C;
		line-height: 34rpx;
		text-align: left;
		font-style: normal;
		margin-top: 16rpx;
	}

	.card {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 64rpx 24rpx 32rpx;
		position: relative;
		margin: 32rpx 24rpx;
	}

	.little {
		position: absolute;
		background: #78FFE6;
		border-radius: 0rpx 0rpx 8rpx 8rpx;
		padding: 4rpx 8rpx;
		font-weight: 500;
		font-size: 20rpx;
		color: #FFFFFF;
		line-height: 32rpx;
		text-align: left;
		font-style: normal;
		position: absolute;
		left: 34rpx;
		top: 0;
	}

	.title {
		font-weight: 500;
		font-size: 32rpx;
		color: #19191A;
		line-height: 44rpx;
		text-align: left;
		font-style: normal;
		padding-bottom: 32rpx;
	}

	.required {
		color: #F53F3F;
	}

	.inner-circle {
		width: 40%;
		height: 40%;
		background: #fff;
		border-radius: 50%;
	}

	.no-options {
		background: #fafafa;
		font-size: 28rpx;
		color: #969896;
		box-sizing: border-box;
		padding: 24rpx;
	}

	.slider {
		display: flex;
		align-items: center;

		.input {
			width: 96rpx;
		}

		&-text {
			display: flex;
			justify-content: space-between;
			font-weight: 400;
			font-size: 20rpx;
			color: #969799;
			line-height: 28rpx;
			text-align: center;
			font-style: normal;
			box-sizing: border-box;
			padding: 0 18px;
		}

		&-right {
			flex: 1;
			position: relative;
		}

		&-ticks {
			position: absolute;
			width: calc(100% - 78rpx);
			left: 18px;
			box-sizing: border-box;
			top: 68rpx;
		}

		&-tick {
			position: absolute;
			width: 2rpx;
			height: 6rpx;
			background: #D6D9DB;
			bottom: 6rpx;
		}

		&-tick__active {
			background: #E3CFA5;
		}

		&-nums {
			position: absolute;
			width: calc(100% - 78rpx);
			left: 18px;
			box-sizing: border-box;
			top: 116rpx;
		}

		&-num {
			position: absolute;
			bottom: 6rpx;
			font-weight: 400;
			font-size: 20rpx;
			color: #969799;
			line-height: 28rpx;
			text-align: center;
			font-style: normal;
		}
	}

	.nfs {
		&-content {
			height: 64rpx;
			display: flex;
			border-radius: 4rpx;
			border: 2rpx solid #EBEDF0;
			background: linear-gradient(90deg, #FFFDF5 0%, #78FFE6 100%);
			position: relative;
		}

		&-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		&-item__inner {
			flex: 1;
			height: 32rpx;
			font-weight: 400;
			font-size: 24rpx;
			line-height: 44rpx;
			text-align: center;
			font-style: normal;
			border-right: 2rpx solid #EBEDF0;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #82511D;
		}

		&-position {
			position: absolute;
			width: 100%;
			height: 100%;
			left: 0;
			top: 0;
			display: flex;
		}

		&-gray {
			color: #969799;
		}

		&-white {
			background: #fff;
		}

		&-transparent {
			background: transparent;
		}

		.no-border_right {
			border-right: none;
		}

		&-text {
			display: flex;
			justify-content: space-between;
			font-weight: 400;
			font-size: 20rpx;
			color: #969799;
			line-height: 28rpx;
			text-align: center;
			font-style: normal;
			box-sizing: border-box;
			margin-bottom: 16rpx;
		}

	}

	.star-word {
		font-weight: 400;
		font-size: 20rpx;
		color: #969799;
		line-height: 28rpx;
		font-style: normal;
		display: flex;
		margin-bottom: 16rpx;
	}

	.matrix-title {
		font-weight: 400;
		font-size: 32rpx;
		color: #141414;
		line-height: 44rpx;
		text-align: left;
		font-style: normal;
		margin-bottom: 32rpx;
	}

	.un-answer {
		background: rgb(255, 51, 0);
		color: #fff;
		line-height: 20px;
		font-size: 12px;
		padding: 3px 7px;
		border-radius: 6px;
		display: inline-block;
		font-weight: bold;
		margin-bottom: 32rpx;
	}

	.ui_uploader_cell {
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		background: #fff;
		border-top: 1rpx solid #e7e7e7;
		min-height: 250rpx;
	}

	.ui_uploader_item {
		position: relative;
		margin-bottom: 8rpx;
	}

	.ui_uploader {
		// margin: 12rpx 0 32rpx 0;
		width: 194rpx;
		height: 194rpx;
		margin-bottom: 4rpx;
		background: #F5F6F7;
		display: flex;
		border-radius: 12rpx;
		justify-content: center;
		align-items: center;
		// margin-left: 12rpx;
	}

	.qr-canvas {
		position: absolute;
		z-index: -10;
		display: none;
		background-color: #fff;
		margin: 0 auto;
		bottom: -100px;
	}

	.imgTips {
		font-size: 24rpx;
		color: #c6c8cc;
		margin-top: 12rpx;
	}
</style>
